package com.qianfeng.android.baoman;

import android.support.v7.app.ActionBarActivity;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuItem;
import android.widget.ListView;

import com.handmark.pulltorefresh.library.PullToRefreshBase;
import com.handmark.pulltorefresh.library.PullToRefreshListView;
import com.lidroid.xutils.DbUtils;
import com.lidroid.xutils.db.sqlite.Selector;
import com.lidroid.xutils.exception.DbException;
import com.qianfeng.android.baoman.adapter.TopicArticleAdapter;
import com.qianfeng.android.baoman.model.Article;

import java.util.LinkedList;
import java.util.List;


public class EnjoyActivity extends BaseActivity implements TopicArticleAdapter.IEnjoyListener {

    private DbUtils dbUtils;
    private LinkedList<Article> articleLinkedList;
    private TopicArticleAdapter articleAdapter;

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_enjoy);

        PullToRefreshListView pullToRefreshListView = (PullToRefreshListView) findViewById(R.id.enjoy_articles);
        pullToRefreshListView.setMode(PullToRefreshBase.Mode.BOTH);
        //listView
        ListView listView = pullToRefreshListView.getRefreshableView();
        articleLinkedList = new LinkedList<>();
        articleAdapter = new TopicArticleAdapter(this, articleLinkedList);
        articleAdapter.setiEnjoyListener(this);
        listView.setAdapter(articleAdapter);
        dbUtils = getDbUtils();
        Selector selector = Selector.from(Article.class)
                .limit(5);
        try {
            List<Article> articles = dbUtils.findAll(selector);
            if (articles != null) {
                articleLinkedList.addAll(articles);
                articleAdapter.notifyDataSetChanged();
            }

        } catch (DbException e) {
            e.printStackTrace();
        }

    }


    @Override
    public void onEnjoy(Article article, Boolean b) {
        try {
            if (b) {
                dbUtils.save(article);
            } else {
                dbUtils.delete(article);
                Selector selector = Selector.from(Article.class)
                        .limit(5);
                List<Article> articles = dbUtils.findAll(selector);
                articleLinkedList.clear();
//                articleLinkedList = (LinkedList) dbUtils.findAll(selector);

                articleLinkedList.addAll(articles);

                articleAdapter.notifyDataSetChanged();
            }
        } catch (Exception e) {
            e.printStackTrace();
        }

    }
}
